Http request asyncronas (threads)

Descripcion

Como realizar peticiones http asyncronas sin tener que esperar a que termine una petición antes de lanzar otra usando threads.

Metodo

El siguiente código hace peticiones asyncronas a una lista de URLs usando un pequeño delay entre peticiones, ademas dentro del thread hay un bucle que hace que se envié cada peticion a una URL dos veces (estas peticiones son sincronas entre si):

import requests
import threading
import time

def make_request(url):

    headers = {"Content-Type": "application/json; charset=utf-8"}
 
    for i in range(0,2):
        data = {
            "id": 1,
            "name": "nombre"
        }

        response = requests.post(url, headers=headers, json=data)
        
        print(f'{url}: {response.status_code}')

print("--- INICIO ---")

# List of URLs to make requests to
urls = [
    "https://www.example.com",
    "https://www.google.com",
    "https://www.wikipedia.org",
    "https://www.python.org"
]

# Create and start threads for each URL
threads = []

for url in urls:
    #Introducimos un pequeño delay entre creación de hilos
    time.sleep(1)
    
    thread = threading.Thread(target=make_request, args=(url,))
    thread.start()
    threads.append(thread)

# Wait for all threads to finish
for thread in threads:
    thread.join()

print("HILOS TERMINADOS")
Tags

Python | Threads | Http